package com.itheima.reggie.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.io.InputStream;

/**
 * oss文件上传工具类
 */
public class OssUtil {
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    static String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    static String accessKeyId = "LTAI5tAi7hDjapjc4s3xRAsK";
    static String accessKeySecret = "R2pQSzj6yqY6l1uEvm8j5PGuHk3b8h";
    static String bucketName = "anti-nanjing";



    public static void create() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        boolean exists = ossClient.doesBucketExist(bucketName);
        System.out.println("exists = " + exists);
        if (!exists) { //判定是否存在此存储空间
            // 创建存储空间。
            ossClient.createBucket(bucketName);
        }
        ossClient.shutdown();
    }


    public static String upload(InputStream inputStream,String fileName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件流。

        ossClient.putObject(bucketName, "images/"+fileName, inputStream);

        // 关闭OSSClient。
        https://anti-nanjing.oss-cn-hangzhou.aliyuncs.com/images
        ossClient.shutdown();
        //返回oss图片url
        String url = "https://" + bucketName + "." + endpoint + "/images/" + fileName;
        return url;
    }
}
